package com.pvdnc.nsocket.server;

import com.pvdnc.nsocket.ManagedChannel;
import com.pvdnc.nsocket.log.SLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import io.netty.channel.Channel;

public class ClientManager {
    private static final SLog LOG =new SLog(ClientManager.class);

    private static final AtomicReference<ClientManager> sInstance=new AtomicReference<>();

    public static ClientManager getInstance(){
        if(sInstance.get()==null)
            sInstance.set(new ClientManager());
        return sInstance.get();
    }

    public final Map<String,ClientProxy> mClientMap=new HashMap<>();

    public void addClient(String name,ClientProxy proxy){
        mClientMap.put(name, proxy);
    }

    public void removeClient(String name){
        mClientMap.remove(name);
    }

    public void removeClient(ClientProxy proxy){
        Set<Map.Entry<String,ClientProxy>> entrySet=mClientMap.entrySet();
        for (Map.Entry<String,ClientProxy> entry:entrySet){
            if(proxy==entry.getValue()) {
                LOG.d("found proxy:"+proxy+" to remove");
                removeClient(entry.getKey());
                break;
            }
        }
    }

    public void removeClient(Channel channel){
        Set<Map.Entry<String,ClientProxy>> entrySet=mClientMap.entrySet();
        for (Map.Entry<String,ClientProxy> entry:entrySet){
            ClientProxy proxy=entry.getValue();
            if(proxy==null)
                continue;
            if(proxy.isSameChannel(channel)) {
                LOG.d("found proxy:"+proxy+" to remove");
                removeClient(entry.getKey());
                break;
            }
        }
    }

    public ClientProxy getClient(String name){
        return mClientMap.get(name);
    }

    public List<String> listClient(){
        return new ArrayList<>(mClientMap.keySet());
    }
}
